package com.example.finaldemo.ui.notifications;

import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.os.CountDownTimer;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.finaldemo.GPT;
import com.example.finaldemo.MsgHelper;
import com.example.finaldemo.R;
import com.example.finaldemo.databinding.FragmentNotificationsBinding;

import java.util.ArrayList;

public class NotificationsFragment extends Fragment {

    private FragmentNotificationsBinding binding;

    ArrayList<String> MsgAll1 = new ArrayList<>();
    private TextView AnswerFromGPT_TextView;
    private Handler UpdateMsg_handler;
    private Runnable Msg_runnable;
    private Handler requestGPT_handler;
    private Runnable GPT_runnable;
    private ArrayAdapter<String> arrayAdapter;
    private String text;
    private boolean isThreadRunning = false;  //线程标志位，避免重复创建
    private String question="给你一段对话，请问这段对话是诈骗的可能性是多少（具体概率），为什么呢？要求回答格式：N/Y(这里写N或者Y,判断是诈骗则返回一个“Y”，判断不是诈骗则返回一个N)+你的分析（尽量分点列出，逻辑清晰，简短，不超过60字）中文（这里开始就是对话了）";
    private String ans = "";
    private GPT gpt = new GPT();





    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        NotificationsViewModel notificationsViewModel =
                new ViewModelProvider(this).get(NotificationsViewModel.class);

        binding = FragmentNotificationsBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        Button button = binding.ok;
        AnswerFromGPT_TextView = binding.Answer;

        Button judge = binding.judge;

        AnswerFromGPT_TextView.setText("Y");

        ListView MsgRecord = binding.MsgRecord;

        arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, new ArrayList<String>());

        MsgRecord.setAdapter(arrayAdapter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestGPT();
                new CountDownTimer(60000, 1000) { // 1分钟，每秒更新一次
                    public void onTick(long millisUntilFinished) {
                        // 这里可以添加倒计时的显示逻辑，比如更新UI上的倒计时文本
                    }

                    public void onFinish() {
                        System.out.println("1分钟结束");
                        // 在倒计时结束时触发button2的点击事件
                        judge.performClick();
                    }
                }.start();
            }
        });

        judge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("judge调用！");
                //诈骗判断
                text = AnswerFromGPT_TextView.getText().toString();
                if (!text.isEmpty()) {
                    // 获取文本的第一个字符
                    char firstChar = text.charAt(0);
                    // 判断第一个字符是否为"Y"
                    if (firstChar == 'Y') {
                        System.out.println("诈骗！");
                        AlertDialog alertDialog1 = new AlertDialog.Builder(requireContext())
                                .setTitle("疑似诈骗！")//标题
                                .setMessage("警告：你收到的信息有诈骗嫌疑！")//内容
                                .setIcon(R.mipmap.ic_launcher)//图标
                                .create();
                        alertDialog1.show();
                    }
                    else
                    {
                    }
                }
                else
                {
                }
            }
        });

        UpdateMsg_handler = new Handler();
        requestGPT_handler = new Handler();
        Msg_runnable = new Runnable() {
            @Override
            public void run() {
                updateMsg();
                UpdateMsg_handler.postDelayed(this, 2000); // 每隔 2 秒执行一次
            }
        };

        GPT_runnable = new Runnable() {
            @Override
            public void run() {
                requestGPT();
                requestGPT_handler.postDelayed(this,300000);
            }
        };

        UpdateMsg_handler.post(Msg_runnable);
        requestGPT_handler.post(GPT_runnable);

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void updateMsg(){
        MsgAll1 = MsgHelper.getMsgList();
        arrayAdapter.clear();
        arrayAdapter.addAll(MsgAll1);
        arrayAdapter.notifyDataSetChanged();
    }

    private void requestGPT(){
        AnswerFromGPT_TextView.setText("");
        //拼接聊天记录
        for (String str: MsgHelper.getMsgList()) {
            question += "["+str+"]";
        }
        if (!isThreadRunning) { // 检查标志位
            isThreadRunning = true; // 设置标志位为true
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 在新线程中执行的代码
                    ans = gpt.answer(question);
                    Handler mainHandler = new Handler(Looper.getMainLooper());
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            AnswerFromGPT_TextView.setText(ans);
                        }
                    });
                    isThreadRunning = false; // 运行结束后将标志位设为false
                }
            }).start();

        }
    }
}